/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/***************************************************************************
 * Name: xmessage.cpp
 *
 * Purpose: message Base API define and implementation
 *
 * Developer:
 *   wen.gu , 2023-07-26
 *
 * TODO:
 *
 ***************************************************************************/

#include "xbus/com/xmessage.h"

namespace xbus::com {

//static 
bool XMessage::CheckMessageHeader(const XMessageHeader& hdr) { /** check message header is right */
    return (hdr.length >= sizeof(hdr)) && (hdr.start_code == XMSG_START_CODE) && 
           (XMSG_GET_PROTOCOL_VER(hdr.flags) == XMSG_PROTOCOL_VER) && (hdr.type != XMSG_UNKNOWN_TYPE); /** todo, is really need check message type?? */
}

//static 
bool XMessage::CheckMessageHeader(const uint8_t* buf , uint32_t size) {
    return (size >= sizeof(XMessageHeader)) && (internal::ByteRead4(buf) == size) &&
           (buf[XMSG_FIELD_OFFSET_STARTCODE] == XMSG_START_CODE_BYTE1) && (buf[XMSG_FIELD_OFFSET_STARTCODE + 1] == XMSG_START_CODE_BYTE2) &&
           (XMSG_GET_PROTOCOL_VER(buf[XMSG_FIELD_OFFSET_FLAGS]) == XMSG_PROTOCOL_VER) &&
           (buf[XMSG_FIELD_OFFSET_TYPE] != XMSG_UNKNOWN_TYPE);
}

//static 
uint32_t XMessage::GetHeaderLength(uint8_t flags) {
    uint32_t hdr_size = sizeof(XMessageHeader);
    if (XMSG_FLAGS_TP_FLAG(flags)) {
        hdr_size += sizeof(XMsgHdrExtPktInfo);
    }

    return hdr_size;
}

void XMessage::InitializeMessageHeader(uint8_t* data, uint32_t length, uint8_t flags) {
    internal::ByteWrite2(data, length);
    data[XMSG_FIELD_OFFSET_STARTCODE] = XMSG_START_CODE_BYTE1;
    data[XMSG_FIELD_OFFSET_STARTCODE + 1] = XMSG_START_CODE_BYTE2;
    data[XMSG_FIELD_OFFSET_FLAGS] = flags;
    memset(data + XMSG_FIELD_OFFSET_TYPE, 0, sizeof(XMessageHeader) - 7);
}

} //namespace xbus::com